package com.levi.test.rpc;

import com.alibaba.fastjson.JSONObject;
import com.levi.test.bean.ExecuteRequest;
import com.levi.test.service.ExecuteService;
import com.levi.test.util.CommonUtils;
import com.levi.test.util.SecretUtil;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.DefaultFullHttpResponse;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.FullHttpResponse;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaderValues;
import io.netty.handler.codec.http.HttpMethod;
import io.netty.handler.codec.http.HttpResponseStatus;
import io.netty.handler.codec.http.HttpUtil;
import io.netty.handler.codec.http.HttpVersion;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.CharsetUtil;

import static com.levi.test.constant.ExecuteCommonData.TEXT_HTML;
import static com.levi.test.constant.ExecuteCommonData.rpcPath;

public class RpcRequestHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) {
        // 获取请求的uri
        String resp = null;
        try {
            String path = req.uri();
            HttpMethod method = req.method();//获取请求方法
            if (!rpcPath.equals(path) || !HttpMethod.POST.equals(method)) {
                resp = "test请求异常";
            } else {
                ByteBuf buf = req.content();
                String reqStr = buf.toString(CharsetUtil.UTF_8);
                reqStr = SecretUtil.secret(reqStr, false);
                ExecuteRequest executeRequest = JSONObject.parseObject(reqStr, ExecuteRequest.class);
                if (executeRequest == null || executeRequest.getC() == null || executeRequest.getM() == null) {
                    resp = "test入参异常：" + reqStr;
                } else {
                    if (executeRequest.getAsyc()) {
                        CommonUtils.executeAsyc(() -> ExecuteService.executeByProxy(executeRequest));
                        resp = "test success";
                    } else {
                        resp = ExecuteService.executeByProxy(executeRequest);
                    }
                }
            }
        } catch (Exception e) {
            System.err.println(e.getMessage());
            resp = e.getMessage();
        }
        writeResponse(ctx, HttpUtil.isKeepAlive(req), resp);
    }

    private static void writeResponse(ChannelHandlerContext ctx, boolean keepAlive, String resp) {
        try {
            if (resp == null) {
                resp = "null";
            }
            ByteBuf byteBuf = Unpooled.copiedBuffer(resp, CharsetUtil.UTF_8);
//            byte[] bytes = SerializableUtil.writeObj(resp);
//            byteBuf = Unpooled.wrappedBuffer(bytes);
            FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuf);
            response.headers().set(HttpHeaderNames.CONTENT_TYPE, TEXT_HTML);
            response.headers().set(HttpHeaderNames.CONTENT_LENGTH, response.content().readableBytes());
            if (keepAlive) {
                response.headers().set(HttpHeaderNames.CONNECTION, HttpHeaderValues.KEEP_ALIVE);
            }
            ctx.writeAndFlush(response);
        } catch (Exception e) {
            System.err.println(e.getMessage());
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.flush();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            ctx.channel().close();
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}

